
import React, { Component, createRef } from 'react'
import { DownOutlined, ExclamationCircleOutlined, } from '@ant-design/icons';
import { Button, Space, Dropdown, Menu, message, Modal, Switch, Popover, } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import MotionLayout from '@/layouts/MotionLayout';
import moment from "moment"
import { OnlineList, OnlineEdit, OnlineDel } from "@/services/online";

import {
  DeleteOutlined,
} from '@ant-design/icons';
import SelectBox from "@/components/SelectBox"
import { SaveTable } from "@/utils/excelHelp"

const actionRef = createRef();



class Page extends Component {
  constructor(props) {
    super(props)
    this.state = {
      SwitchIsEnable: false,
      createModalVisible: false,
      updateModalVisible: false,
      selectRow: {},
      params: {},
    }
  }

  async handleDeal({ fields, serviceMethod, type = "添加" }) {
    const hide = message.loading(`正在${type}`);
    try {
      const res = await serviceMethod(fields);
      hide();
      if (!res.success) {
        message.error(`${type}失败，${res.result}`);
        return false;
      }
      message.success(`${type}成功`);
      return true;
    } catch (error) {
      hide();
      message.error(`${type}异常，${error}`);
      return false;
    }
  }
  async getDataSource(params) {
    const { result, success } = await OnlineList({
      ...params,
      page: params.current,
      limit: params.pageSize,
    })
    if (!success) {
      return {
        data: [],
        page: 1,
        success: false,
        total: 0,
      };
    }
    this.setState({
      params,
    })
    return {
      data: result.arr,
      page: 1,
      success: true,
      total: result.count,
    };
  }
  createColumns() {
    return [
      {
        title: '姓名',
        dataIndex: 'trueName',
      },
      {
        title: '手机号',
        dataIndex: 'phoneCode',
      },
      {
        title: '中考报名号',
        dataIndex: 'temp1',
        hideInSearch: true,
      },
      {
        title: '中考分数',
        dataIndex: 'temp2',
        hideInSearch: true,
      },
      {
        title: '报名专业',
        dataIndex: 'temp3',
        hideInSearch: true,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        valueType: 'dateTime',
        render: text => moment(text).format("YYYY-MM-DD HH:mm"),
        hideInSearch: true,
      },
      {
        title: '通知书编号',
        dataIndex: 'temp4',
        hideInSearch: true,
      },
      // {
      //   title: '审核时间',
      //   dataIndex: 'updateTime',
      //   valueType: 'dateTime',
      //   render: text => moment(text).format("YYYY-MM-DD HH:mm"),
      //   hideInSearch:true,
      // },
      {
        title: '是否可用',
        dataIndex: 'isEnable',
        hideInTable: true,
        valueEnum: {
          [false]: {
            text: '未审核',
            status: 'Default',
          },
          [true]: {
            text: '已审核',
            status: 'Processing',
          },
        },
      },
      {
        title: '审核状态',
        dataIndex: 'isEnable1',
        hideInSearch: true,
        render: (_, row) => {
          // console.log(_,row)
          return (<Switch disabled={this.state.SwitchIsEnable}
            checkedChildren={"已审核"} unCheckedChildren={"未审核"}
            onChange={async (isEnable) => {
              const success = await this.handleDeal({
                type: "操作",
                fields: {
                  id: row.id,
                  isEnable: isEnable,
                },
                serviceMethod: OnlineEdit,
              });
              if (!success) {
                return;
              }
              if (!actionRef.current) {
                return;
              }
              actionRef.current.reload();
            }}
            checked={row.isEnable}
          // defaultChecked={_}
          />)
        }
      },
      {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        render: (_, row) => (
          <Space>
            <Button
              onClick={(e) => {
                e.stopPropagation();
                Modal.confirm({
                  title: '是否确认删除?',
                  icon: <ExclamationCircleOutlined />,
                  onOk: async () => {
                    const idList = {
                      "id": [
                        row.id
                      ]
                    };
                    const success = await this.handleDeal({
                      type: "删除",
                      fields: idList,
                      serviceMethod: OnlineDel,
                    });
                    if (!success) {
                      return;
                    }
                    if (!actionRef.current) {
                      return;
                    }
                    actionRef.current.reload();
                  },
                });
              }}
              size="small" type="primary" icon={<DeleteOutlined />}></Button>
          </Space>
        ),
      },
    ];
  }

  render() {


    return (
      <PageHeaderWrapper>
        <MotionLayout>
          <ProTable
            actionRef={actionRef}
            headerTitle={""}
            rowKey="id"
            params={{}}
            request={async (params) => this.getDataSource(params)}
            columns={this.createColumns()}
            rowSelection={{}}
            pagination={{
              pageSize: 10,
            }}

            toolBarRender={(action, { selectedRowKeys, selectedRows }) => {
              return ([
                <Popover
                  content={<SelectBox
                    Submit={async (arr) => {
                      const res = await OnlineList({
                        ...this.state.params,
                        page: 1,
                        limit: 10000,
                      })
                      if (!res.success) {
                        message.error(`${type}失败，${res.result}`);
                        return;
                      }
                      let mapping = {};
                      arr.forEach(ele => {
                        mapping[ele.value] = ele.label;
                      })
                      SaveTable({
                        arr: res.result.arr,
                        mapping,
                      })
                    }}
                    arr={this.createColumns().map(item => ({ label: item.title, value: item.dataIndex }))} />}
                  title="选择要导出的字段"
                  trigger="click">
                  <Button>导出</Button>
                </Popover>,
                selectedRowKeys && selectedRowKeys.length > 0 && (
                  <Dropdown
                    overlay={
                      <Menu
                        onClick={async e => {
                          if (e.key === 'remove') {
                            const idList = {
                              "id": selectedRowKeys
                            };
                            Modal.confirm({
                              title: '是否确认删除?',
                              icon: <ExclamationCircleOutlined />,
                              onOk: async () => {
                                const success = await this.handleDeal({
                                  type: "删除",
                                  fields: idList,
                                  serviceMethod: OnlineDel
                                });
                                if (!success) {
                                  return;
                                }
                                if (!actionRef.current) {
                                  return;
                                }
                                actionRef.current.reload();
                              },
                            });
                          }
                        }}
                        selectedKeys={[]}
                      >
                        <Menu.Item key="remove">批量删除</Menu.Item>
                        <Menu.Item key="approval">批量审批</Menu.Item>
                      </Menu>
                    }
                  >
                    <Button>
                      批量操作 <DownOutlined />
                    </Button>
                  </Dropdown>
                ),
              ]);
            }}
          />
        </MotionLayout>
      </PageHeaderWrapper>
    )
  }
}
export default Page
